<template>
    <van-button
    v-if="isFollowed"
    class="follow-btn"
    round size="small"
    :loading="followLoading"
    @click="onFollow">
        已关注
    </van-button>

    <van-button
    v-else
    class="follow-btn"
    type="info"
    color="#3296fa"
    round size="small"
    icon="plus"
    :loading="followLoading"
    @click="onFollow">
        关注
    </van-button>
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'

export default {
    name: 'FollowUser',
    props: ['isFollowed', 'userId'],
    model: {
        prop: 'isFollowed',
        event: 'updateFollowed'
    },
    data () {
        return {
            followLoading: false
        }
    },
    methods: {
        async onFollow () {
            this.followLoading = true
            try {
                if (this.isFollowed) {
                    // 已关注，取消关注
                    await deleteFollow(this.userId)
                } else {
                    // 未关注，添加关注
                    await addFollow(this.userId)
                }
                // this.isFollowed = !this.isFollowed
                this.$emit('updateFollowed', !this.isFollowed)
             } catch (err) {
                if (err.response && err.response.status === 400) {
                    return this.$toast('你不能关注你自己')
                }
                this.$toast('操作失败，请重试')
            }
            this.followLoading = false
        }
    }
}
</script>

<style></style>
